package com.xgimi.locales.bean

import com.xgimi.locales.utils.Constant
import com.xgimi.locales.utils.gson
import java.util.*

class RowBean {

    // langs["xml_name"]=
    // langs["id"]=
    // langs["en-rGB"] = "Auto Focus on Startup"
    // langs["ja"] = "起動時の自動焦点"
    // langs["zh-rCN"] = "开机自动对焦"
    val langs: TreeMap<String, String> = TreeMap()

    var rowAttr: RowAttr? = null

    fun getRowAttrValue() {
        if (langs.containsKey(Constant.FIELD_PROPERTY)) {
            val property = langs[Constant.FIELD_PROPERTY]
            try { // 解析json {"keyName":"projection_mode","arrayItemIndex",0,...}
                rowAttr = gson.fromJson(property, RowAttr::class.java)
            } catch (e:Exception) {
                e.printStackTrace()
                println("error:${e.message}")
            }
        } else { // 处理 xml_name,id 相关属性，兼容 python脚本
            rowAttr = RowAttr()
            val xmlName = langs[Constant.XML_NAME_TITLE]
            val id = langs[Constant.ID_TITLE]
            rowAttr?.also {
                it.isArray = xmlName == Constant.ARRAY_XML_NAME
                if (it.isArray) { // string-array
                    val ids = id?.split("-")
                    it.arrayItemIndex = ids?.get(2)?.toInt() ?: -1
                    it.keyName = ids?.get(0)
                } else { // string
                    it.keyName = id
                }
            }
//            println("initRowAttr xmlName:$xmlName id:$id rowAttr:$rowAttr")
        }
    }

//    private fun setRowAttrValue(rowAttr: RowAttr?) {
//        try {
//            val property: String = gson.toJson(rowAttr)
//            langs[Constant.FIELD_PROPERTY] = property
//        } catch (e: java.lang.Exception) {
//            e.printStackTrace()
//        }
//    }

    fun syncRowAttr() {
        try {
            val property: String = gson.toJson(rowAttr)
            langs[Constant.FIELD_PROPERTY] = property
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    override fun toString(): String {
        return "RowBean(langs=$langs, rowAttr=$rowAttr)"
    }

}